#!/usr/bin/python
# auth.py
# Copyright (C) Vincenzo Tilotta 2011 <tailot@gmail.com>
#
# auth.py is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# auth.py is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

import random, os, urllib2, urllib, time, subprocess
from util import *
from defs import *
def randstring(sizerand):
	password = ''.join([random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890') for i in range(sizerand)])
	return password
def auth(fd_ssl):
	mytime = ( time.ctime() ).replace(" ","")
	infohome = NAMECONFIG
	#Se il client e' la prima volta che si connette si registra e riceve una chiave rsa pub con cui comunicare
	if(os.path.exists(infohome) == False):
		os.mkdir(infohome)
		genuser = ''
		connkey = ''
		os.system("openssl genrsa -out "+infohome+"/key.key 2048");
		os.system("openssl rsa -in "+infohome+"/key.key -pubout -out "+infohome+"/key.pubkey");
		fd_pubkey = open(infohome+"/key.pubkey","r")
		pubkey = fd_pubkey.read()
		fd_pubkey.close()
		while(1):
			genuser = randstring(24)
			data = urllib.urlencode({'u': genuser,'p': pubkey})
			req = urllib2.Request(URLAUTH)
			fd = urllib2.urlopen(req, data)
			connkey = fd.read()
			if(connkey != "0"):
				break
		#registro i dati con cui ho registrato il client
		fput(infohome+"/"+"user",genuser)
	user = fread(infohome+"/"+"user")
	fd_ssl.write("login\n"+user+"\n")
	fput("sendchallenge",fd_ssl.read())
	os.system("openssl rsautl -decrypt -in sendchallenge -inkey "+infohome+"/key.key > "+mytime)
	decmess = fread(mytime)
	#manca da eliminare oksend
	os.remove("sendchallenge")
	fd_ssl.write(decmess)
	return mytime
